# RUN01_Tushare_Pull_Datas_to_SQLITE3_s_Stocks_Daily.py
# Create by GF 2025-08-12 12:55

import re
import traceback
# ..................................................
import pandas  # Pandas 2.0.3
# ..................................................
import GF_PY3_CLASS_Wrapper_SQLAlchemy_2_x
import GF_PY3_CLASS_Wrapper_Tushare

# ##################################################

def Tushare_1_4_x_Pull_Datas_to_SQLITE3_s_Stocks_Daily(SQLite_Path:str, Input_Date:str) -> dict:

    if (('-' not in Input_Date) or (len(Input_Date) < 10)):
        return {"error": "<Input_Date> Format Should be <YYYY-mm-dd>, Example: 2025-01-01"}

    # 初始化 SQLite 连接
    # ..............................................
    w_sqlalchemy = GF_PY3_CLASS_Wrapper_SQLAlchemy_2_x.wrapper_sqlalchemy_2_x()
    w_sqlalchemy.db_path.update(SQLite_Path)

    # 查询 Tusahre API Key
    df = w_sqlalchemy.sqlite_3_x_query("SELECT value FROM vars WHERE name = 'tushare_api_key';")
    # ..............................................
    TUSHARE_API_KEY = df["value"][0]

    # 查询 Logs 中特定日期的数据插入记录
    sql_statment = f"SELECT COUNT(*) AS rows_count FROM logs WHERE time = '{Input_Date}' AND memo REGEXP '.*日数据.*|.*不复权.*';"
    df = w_sqlalchemy.sqlite_3_x_query(sql_statment)
    # ..............................................
    logs_existing_rows_count = df["rows_count"][0]

    df = pandas.DataFrame()
    if (logs_existing_rows_count == 0): # 如果日志 (dateset.logs) 中存在的行数 == 0, 则获取 Tushare API 数据
        time_range = (Input_Date.replace('-', ''), Input_Date.replace('-', ''))
        # ..........................................
        w_tushare = GF_PY3_CLASS_Wrapper_Tushare.wrapper_tushare_1_4_x()
    #   w_tushare.api_key.update("11846e11107317715e00136d10961e331671a75810d11d111111d11e")
        w_tushare.api_key.update(TUSHARE_API_KEY)
        w_tushare.adjusted.update(None)
        w_tushare.start_date.update(time_range[0])
        w_tushare.end_date.update(time_range[1])
        # ..........................................
        df = w_tushare.get_stock_daily()
        # ..........................................
        df["date"] = pandas.to_datetime(df["trade_date"], format="%Y%m%d")
        df["time"] = df["date"].dt.strftime("%Y-%m-%d")  # 将日期时间格式转换为字符串格式
        df["memo"] = "日数据/不复权"
        df = df.drop(["trade_date", "date"], axis=1)

    affected_number_of_dist = w_sqlalchemy.sqlite_3_x_append_DataFrame(df, "tushare_api_cache_en_us")

    affected_number_of_logs = 0
    if (affected_number_of_dist >= 1): # 如果被影响行数 >= 1, 则写入日志 (dateset.logs)
        df = pandas.DataFrame({
            "time"     : [Input_Date],
            "object"   : ["tushare_api_cache_en_us"],
            "event"    : ["insert"],
            "afct_num" : [affected_number_of_dist],
            "unit"     : ["row"],
            "memo"     : ["日数据/不复权"]
        })
        # ..........................................
        affected_number_of_logs = w_sqlalchemy.sqlite_3_x_append_DataFrame(df, "logs")

    return {"affected_number_of_dist": affected_number_of_dist, "affected_number_of_logs": affected_number_of_logs}

# ##################################################

# KNOWLEDGE:
# 16 进制空格字符 ----> \x20
# Unicode 空格字符 ---> \u0020

# ##################################################

try:

    print(f"""[DEBUG] Tushare Pull Datas to SQLite 20250812 版""")
    print(f"""==================================================""")
    print(f"""[DEBUG] 输入 <任意数字> 并按 <Enter> 开始任务""")
    Inputed = input()

    print(f"""[DEBUG] <日期> 说明: 格式 YYYY-mm-dd, 格式示例 2025-01-01""")
    print(f"""[DEBUG] <日期> 说明: 使用 \\x20 (16 进制空格) 或 \\u0020 (Unicode 空格) 分隔""")
    print(f"""[DEBUG] <日期> 说明: 可输入单个或多个日期, 单日期 2025-01-01, 多日期 2025-01-01 2025-01-02 ...""")
    print(f"""[DEBUG] 输入 <日期>:""")
    Inputed = input()
    Inputed = re.sub("\x20+",   '+', Inputed)  # 替换 16 进制空格
    Inputed = re.sub("\u0020+", '+', Inputed)  # 替换 Unicode 空格
    Inputed = Inputed.split('+')

    for x in Inputed:
        y = Tushare_1_4_x_Pull_Datas_to_SQLITE3_s_Stocks_Daily(SQLite_Path = "./GF_SQLITE3_FINANCE.db", Input_Date = x)
        print(f"""[DEBUG] INPUT: {x}, RETURN: {y}""")

    print(f"""[DEBUG] 数据库: SQLITE3_DATASET.db 已更新""")
    print(f"""==================================================""")
    print(f"""[DEBUG] 输入 <任意数字> 并按 <Enter> 退出程序""")
    Inputed = input()

except Exception as e:

    print(f"""[DEBUG] 发生异常""")
    print(f"""==================================================""")
    traceback.print_exc()  # 打印异常信息到控制台, 而不是引发异常后退出
    print(f"""==================================================""")
    print(f"""[DEBUG] 输入 <任意数字> 并按 <Enter> 退出程序""")
    Inputed = input()

# Signed by GF.
